import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  TextInput,
  TouchableOpacity,
  Platform,
  Dimensions,
} from 'react-native';

import styles from '../order/editOrderStyle';
import CustomListView from '../global/CustomListView';
import ToastTip from '../global/ToastTip';
import ListViewActivityIndicator from '../global/ListViewActivityIndicator';
import api from '../../services/api';
import _ from 'lodash';
import Communications from 'react-native-communications';

const {width: deviceWidth, height: deviceHeight} = Dimensions.get('window');

class OwnerList extends Component {
    constructor(props) {
		super(props);

		this.state = {
			currentPage: 1,
            noData: false,
            totalCount: 0,
            dataList:[],
		};

        this.totalpage = 0;
        this.pagesize = 10;
        this.totalCount = 0;
        this.list = [];
	}

    componentDidMount() {
        this._mounted = true;
        this.onLoad();
    }

    onLoad(){
        if(this.state.noData){
            this.setState({ noData: false});
        }

        this._withdrawByList._pullToRefreshListView.beginRefresh(true);
    }

    componentWillUnmount () {
        this._mounted = false;
        this.timeIndex && clearTimeout(this.timeIndex);
    }

    async _getWithdrawList(){
        let list;

        this.setState({ currentPage: 1 });
        list = await api.post('/housekeeper/ownerlist', {
                       page:1,
                       pagesize: this.pagesize
                    });

        if(list.cd == 1){
            this.refs.toast.show(list.msg);
            this._withdrawByList._pullToRefreshListView.endRefresh(false);
            return;
        }

       if(Platform.OS == 'ios') {
           this._endWithdrawList(list.data);
       } else {
           this.timeIndex = setTimeout(() => {
               this._endWithdrawList(list.data);
           }, 200);
       }
    }

    _endWithdrawList(list){

        this.totalpage = list.total_page;
        this.list = list.res;

        if(!this._mounted){
            return;
        }

        if(this.list.length==0){
            this.setState({noData: true});
            return;
        }

        this._withdrawByList.setState({
            dataList: list.res,
            dataSource: this._withdrawByList._dataSource.cloneWithRows(list.res)
        });

        // this.totalCount = list.count;

        this.setState({totalCount: list.count, dataList: list.res});

        this._activityIndicator.setState({ visible: false,});
        this._withdrawByList._pullToRefreshListView.endRefresh(false);
    }

    async _retrieveNextPage() {
		if (this.state.currentPage !== this.totalpage) {

			let page;
            page = this.state.currentPage + 1;
            this.setState({ currentPage: page });

            let list;
            list = await api.post('/housekeeper/ownerlist', {
                           page:page,
                           pagesize: this.pagesize
                        });

            if(list.cd == 1){
                this.refs.toast.show(list.msg);
                this._withdrawByList._pullToRefreshListView.endRefresh(false);
                return;
            }

        //    const data = this.list;
           const newData = list.data.res;
           newData.map((item, index) => this.list.push(item));

           this._withdrawByList.setState({
               dataList: this.list,
               dataSource: this._withdrawByList._dataSource.cloneWithRows(this.list),
           });
           this._withdrawByList._pullToRefreshListView.endLoadMore(false);

        }else{
            this._withdrawByList._pullToRefreshListView.endLoadMore(true);
        }
	}

    _onRefresh(){
        this._getWithdrawList();
    }

    _onLoadMore(){
        this._retrieveNextPage();
    }

    _firePhone(phone){
        Communications.phonecall(phone, true);
    }

    _renderRow(rowData, sectionID, rowID){

        return (
            <View style={{marginLeft:15,paddingTop:15,paddingBottom:15,flexDirection: 'row',alignItems:'center',borderBottomWidth: StyleSheet.hairlineWidth, borderColor: "#DEDEDE"}}>
                <View style={{borderRightWidth: StyleSheet.hairlineWidth, borderColor: "#DEDEDE",flex:1}}>
                    <Text style={{fontSize: 18, color: '#555555',}}>{rowData.name}<Text style={{fontSize:15, color: '#7B7B7B',marginLeft:11}}>{rowData.role==1?"业主":(rowData.role==2?"租客":"员工")}</Text></Text>
                    <Text style={{fontSize: 15, color: '#7B7B7B', marginTop: 6, }}>{rowData.homeAddress}</Text>
                </View>
                <TouchableOpacity onPress={this._firePhone.bind(this, rowData.phone)} style={{justifyContent: 'flex-end',marginRight:22,marginLeft:22}}>
                    <Image source={require('../../../img/hk_phone_icon.png')}/>
                </TouchableOpacity>
            </View>
        );
    }

    _renderNodata(){
        return (
            <View style={{alignItems:'center',justifyContent:'center',flex:1,backgroundColor:'#fff'}}>
                <Image source={require('../../../img/hk_nodata_icon.png')} style={styles.leftImage}/>
                <Text style={{fontSize: 13, color: '#B5B5B5',marginTop:10}}>暂无业主</Text>
            </View>
        );
    }

    render() {
        return (
            this.state.noData?this._renderNodata():
            <View style={{flex: 1, backgroundColor: '#f3f3f3',}}>
                <View style={{paddingTop:10,paddingBottom:10,borderBottomWidth: StyleSheet.hairlineWidth, borderColor: "#DEDEDE"}}>
                    <Text style={{fontSize: 15, color: '#7B7B7B',textAlign:'center'}}>已注册业主：{this.state.totalCount}人</Text>
                </View>
                <CustomListView
                    ref={ (component) => this._withdrawByList = component }
                    dataList={this.state.dataList}
                    onRefresh={this._onRefresh.bind(this)}
                    onLoadMore={this._onLoadMore.bind(this)}
                    renderRow ={this._renderRow.bind(this)}
                />
                <ListViewActivityIndicator
                    ref={ (component) => this._activityIndicator = component }
                    style={{marginRight: 10, position:'absolute', left: (deviceWidth - 20) / 2, top: (deviceHeight - 64 - 70) / 2, }}
                    color={'#a9a9a9'}/>
                <ToastTip ref="toast" offsetY={160}/>
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
OwnerList = connectHelper(state => state)(OwnerList);

module.exports = OwnerList;
